package com.desire.config;

import com.baomidou.mybatisplus.core.config.GlobalConfig;
import com.baomidou.mybatisplus.extension.spring.MybatisSqlSessionFactoryBean;
import com.zaxxer.hikari.HikariDataSource;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.*;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;

import java.io.IOException;

/**
 * @author LittleDesire
 * @description
 * @date 2022-04-15 周五 23:02
 * @since 17
 */
@Configuration
@ComponentScan("com.desire.mapper")
@MapperScan("com.desire.mapper")
@PropertySource("classpath:jdbcConfig.properties")
public class MpConfig {
    @Value("${jdbc.driver}")
    private String driver;
    @Value("${jdbc.url}")
    private String url;
    @Value("${jdbc.username}")
    private String username;
    @Value("${jdbc.password}")
    private String password;

    @Bean(value = "ds", destroyMethod = "close")
    @Primary
    public HikariDataSource ds() {
        HikariDataSource ds = new HikariDataSource();
        ds.setUsername(username);
        ds.setJdbcUrl(url);
        ds.setPassword(password);
        ds.setDriverClassName(driver);
        return ds;
    }

    @Bean(value = "sf")
    public MybatisSqlSessionFactoryBean sf(HikariDataSource ds) throws IOException {
        MybatisSqlSessionFactoryBean sf = new MybatisSqlSessionFactoryBean();
        sf.setDataSource(ds);
        GlobalConfig gc = new GlobalConfig();
        gc.setBanner(true);
        sf.setGlobalConfig(gc);
        Resource[] resources = new PathMatchingResourcePatternResolver().getResources("classpath*:mapper/*Mapper*.xml");
        sf.setMapperLocations(resources);
        return sf;
    }
}
